#include "GenericMessage.h"

#include <string>
using namespace std; 


namespace messaging{
GenericMessage::GenericMessage(const char* msg)
{
	content = msg; 
	vector<string> tokens; 
	tokenize(content, tokens, " "); 
	content = tokens.back().substr(5); 

	string& toStr = tokens[0]; 
	string& fromStr  = tokens[1]; 
	string& cmdStr  = tokens[2]; 

	toStr = toStr.substr(toStr.find("=")+1); 
	fromStr = fromStr.substr(fromStr.find("=")+1); 
	cmdStr = cmdStr.substr(cmdStr.find("=")+1); 

	int tmp; 
	sscanf(toStr.data(), "%d", &tmp); 
	to = (MessageRecipient) tmp; 

	sscanf(fromStr.data(), "%d", &tmp); 
	from = (MessageRecipient) tmp; 

	sscanf(cmdStr.data(), "%d", &tmp); 
	cmd = (MessageType) tmp; 

}


GenericMessage::GenericMessage(MessageRecipient pfrom, MessageRecipient pto, MessageType pcmd, ValueType pvalType)
{
	from = pfrom; 
	to   = pto; 
	cmd  = pcmd; 
	valType = pvalType; 

	content = ""; 
}


GenericMessage::~GenericMessage(void)
{
}


void GenericMessage::setContent(string& s)
{
	content = s; 
}


void GenericMessage::tokenize(const string& str, vector<string> & tokens, const string& delimiters)
{
    // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
    string::size_type pos     = str.find_first_of(delimiters, lastPos);

	int ind = 0; 

    while ( string::npos != pos || string::npos != lastPos )
    {
		ind++; 
        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiters, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
    }
}


int GenericMessage::str2int(string& str) const
{	
	int result ; 
	sscanf(str.data(), "%d", &result);
	return result; 
}

double GenericMessage::str2double(string& str) const
{	
	double result ; 
	sscanf(str.data(), "%lf", &result);
	return result; 
}


const char* GenericMessage::toString()
{
	printf("from: %d\n", from); 
	printf("to  : %d\n", to); 
	printf("cmd: %d\n", cmd); 
	return ""; 
}

string GenericMessage::makeMessage()
{
	string result = ""; 
	char* tmpStr = new char [20]; 

	sprintf(tmpStr, "TO=%d ", (int) to); 
	result.append(tmpStr); 

	sprintf(tmpStr, "FROM=%d ", (int) from); 
	result.append(tmpStr); 

	sprintf(tmpStr, "CMD=%d ", (int) cmd); 
	result.append(tmpStr); 

	sprintf(tmpStr, "VALTYPE=%d ", (int) valType); 
	result.append(tmpStr); 

	result.append("VALS=");
	result.append(content); 

	return result; 
}
}
